#!/usr/bin/python
# -*- encoding: utf-8 -*-

"""
@File:      tc_nettle_nettle_func_009.py
@Time:      2024/04/08 14:51:50
@Author:    zhixin
@Version:   1.0
@Contact:   zx01468051@alibaba-inc.com
@License:   Mulan PSL v2
@Modify:    zhixin
"""

from common.basetest import LocalTest
import re

class Test(LocalTest):
    """
    See tc_nettle_nettle_func_009.yaml for details

    :avocado: tags=P2,noarch,local,fix
    """
    PARAM_DIC = {"pkg_name": "nettle nettle-devel gcc"}
    def setUp(self):
        super().setUp(self.PARAM_DIC)
        cmdline = """cat > nettle_test9.c <<EOF
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <string.h>
#include <nettle/sha.h>

#define THREADS_COUNT 5
#define ITERATIONS_PER_THREAD 100

// 全局共享的SHA256上下文
struct sha256_ctx global_sha256_context;
pthread_mutex_t mutex;  // 用于保护共享上下文的互斥锁

// 线程工作函数
void *thread_work(void *thread_id) {
    long t_id = (long)thread_id;
    uint8_t digest[SHA256_DIGEST_SIZE];

    printf("线程 #%ld: 开始执行...\\n", t_id);
    const char *message = "测试消息";

    for (int i = 0; i < ITERATIONS_PER_THREAD; ++i) {
        // 上锁
        pthread_mutex_lock(&mutex);

        // 如果是第一个线程，重置全局SHA256上下文
        if (t_id == 0 && i == 0) {
            sha256_init(&global_sha256_context);
        }

        sha256_update(&global_sha256_context, strlen(message), (uint8_t *)message);


        // 解锁
        pthread_mutex_unlock(&mutex);

        // 每个线程单独计算并打印摘要
        struct sha256_ctx private_ctx = global_sha256_context;  // 复制共享上下文到私有上下文
        sha256_digest(&private_ctx, SHA256_DIGEST_SIZE, digest);

        printf("线程 #%ld: 迭代 #%d 的摘要: ", t_id, i);
        for (size_t j = 0; j < SHA256_DIGEST_SIZE; j++) {
            printf("%02x", digest[j]);
        }
        printf("\\n");
    }

    printf("线程 #%ld: 结束执行。\n", t_id);
    pthread_exit(NULL);
}

int main() {
    pthread_t threads[THREADS_COUNT];
    pthread_mutex_init(&mutex, NULL);

    // 创建线程
    for (long i = 0; i < THREADS_COUNT; ++i) {
        int rc = pthread_create(&threads[i], NULL, thread_work, (void *)i);
        if (rc) {
            printf("ERROR; 返回码是 %d\\n", rc);
            exit(-1);
        }
    }

    // 等待线程结束
    for (long i = 0; i < THREADS_COUNT; ++i) {
        pthread_join(threads[i], NULL);
    }

    printf("所有线程执行完成。\\n");

    // 清理并退出
    pthread_mutex_destroy(&mutex);
    pthread_exit(NULL);
}
EOF"""

        self.cmd(cmdline)
    
    def test(self):
        self.cmd('gcc -o nettle_test9 nettle_test9.c -lnettle -pthread')
        code, nettle_result = self.cmd("./nettle_test9")
        self.assertIn('所有线程执行完成', nettle_result)


    def tearDown(self):
        super().tearDown(self.PARAM_DIC)
        self.cmd('rm -rf nettle_test9 nettle_test9.c')
